var http = require('http');
var fs = require('fs');
var tem = require('art-template')
var url = require('url');
var showdata = [{
  name: '郭佳佳',
  age: '23',
  sex: 'women',
  status: 'girlfriend'
}, {
  name: '谭明',
  age: '23',
  sex: 'man',
  status: 'boyfriend'
}]
http
  .createServer(function (req, res) {
    //var url = req.url;
    var urlpasreData = url.parse(req.url, true);
    var pathname = urlpasreData.pathname;
    if (pathname === '/') {
      res.setHeader('Content-Type', 'text/plain;charset=utf-8')
      res.end(JSON.stringify(showdata))
    } else if (pathname === '/index') {
      fs.readFile('index.html', function (err, data) {
        if (err) {
          console.log('this file had read error');
        } else {
          let temrend = tem.render(data.toString(), {
            showdata: showdata
          })
          res.setHeader('Content-Type', 'text/html;charset=utf-8');
          res.end(temrend)
        }
      })//注意请求路径之前必须写/
    } else if (pathname.indexOf('/public/') === 0) {
      /*             fs.readFile('.' + url, function (err, data) {
                      if (err) {
                          res.end('css file read error');
                      } else {
                          res.end(data)
                      }
                  }) */
      if (pathname.indexOf('/public/css') === 0) {
        fs.readFile('./public/normal.css', function (err, data) {
          if (err) {
            res.end('css file read error');
          } else {
            res.setHeader('Content-Type', 'text/css');
            res.end(data)
          }
        })
      } else if (pathname.indexOf('/public/img') === 0) {
        fs.readFile('./public/img/mygirl.jpg', function (err, data) {
          if (err) {
            res.end('img file read error')
          } else {
            res.setHeader('Content-Type', 'text/x-img');
            res.end(data)
          }
        })
      }

    } else if (pathname === '/post') {
      fs.readFile('./post.html', function (err, data) {
        if (err) {
          res.end('post.html read failed')
        } else {
          res.end(data)
        }
      })
    } else if (pathname === '/pushtalk') {
      //解构，保证传的值的格式
      let { name, age } = urlpasreData.query
      showdata.push({ name, age })
      //临时重定向，1.状态码302，2.响应头中告诉客户端location
      //302自动响应，发生跳转
      res.statusCode = 302;
      res.setHeader('Location', '/index')
      res.end()
    }
    else {
      fs.readFile('./404.html', function (err, data) {
        if (err) {
          res.end('this file read failed');
        } else {
          res.setHeader('Content-Type', 'text/html;charset=utf-8');
          res.end(data);
        }
      })
    }
  })
  .listen(3000, function () {
    console.log('Serve is running......');
  })